<?php

namespace App\Http\Controllers\Api\SmallApp\Register;

use App\Http\Controllers\Common\ApiController;
use App\Models\User\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class RegisterController extends ApiController {

    public function add(Request $request) {
        $phone = $request->input('phone');
        $verify_code = $request->input('verify_code');
        $password = $request->input('password');

        $this->validate($request, [
            'phone'=>'required|unique:App\Models\User\User,phone|regex:/^1[3456789]\d{9}$/',
            'verify_code'=>'required|integer',
            //'password'=>'required|between:8,16|regex:/^(?![A-Z]+$)(?![a-z]+$)(?!\d+$)(?![\W_]+$)\S+$/',
            'password'=>'required|between:8,16',
            //confirmed
        ]);
        if(env('APP_ENV')!='test'){
            $key = "verifyCode:$phone:$verify_code";
            if(Redis::exists($key)!=1){
                return responseFail('验证码错误！');
            }
        }

        $password = md5($password);
        $user = User::create(compact('phone','password'));
        $user->token = createNewToken($user->id);
        return responseSuccess($user->toArray());

    }

    public function getVerifyCode(Request $request) {
        $phone = $request->input('phone');
        $this->validate($request, [
            'phone'=>'required|regex:/^1[3456789]\d{9}$/',
        ]);
        if(env('APP_ENV','test')=='test'){
            $verifyCode = rand(1000,9999);
            return responseSuccess(compact('verifyCode'));
        }else{
            sendVerifyCode($phone);
            return responseSuccess();
        }
    }
}
